<template>
  <div id="app" class="container">
    <div class="row">
      <div class="col-md-8 col-md-offset-2">
        <Alert v-bind:error="error" />
      </div>
    </div>
    <div class="row">
      <div class="col-md-8 col-md-offset-2">
        <header>
          <h2 class="page-header">七叶<small> - 待办任务</small></h2>
        </header>
      </div>
    </div>
    <div class="row">
      <div class="col-md-8 col-md-offset-2">
        <TodoInput v-on:on-add-todo="handleAddTodo" v-bind:hasError="error.has" />
      </div>
    </div>
    <div class="row">
      <div class="col-md-8 col-md-offset-2">
        <TodoList
          v-bind:todos="todos"
          v-bind:total="total"
          v-bind:finished="finished"
          v-on:on-del-todo="handleDelTodo"
          v-on:on-change-todo="handleChangeTodo"
          v-on:on-save-todo="handleSaveTodo"
          v-on:on-clear-todo="handleClearTodo" />
      </div>
    </div>
  </div>
</template>

<script>
// 程序根组件，包含其他组件 - 使用vuex的版本
import Alert from './components/Alert'
import TodoInput from './components/TodoInput'
import TodoList from './components/TodoList'
import {mapState, mapGetters, mapActions} from "vuex"

export default {
  name: 'app',
  components: {
    Alert,
    TodoInput,
    TodoList
  },
  data() {
    return {
      error: {
        has: false,
        message: ''
      }
    }
  },
  computed: { // 仓库中的数据映射到当前组件
    ...mapGetters(['total', 'finished']),
    ...mapState(['todos'])
  },
  created() {
    this._loadTodoFromStorage()
  },
  methods: { // 仓库中的动作映射到当前组件
    ...mapActions([
      'initTodo',
      'addTodo',
      'delTodo',
      'changeTodo'
    ]),
    // 以下是组件自定义函数
    handleAddTodo(content) {
      if (!content) {
        this._setError(true, '请输入代办任务！')
        return;
      }
      this._initError();
      this.addTodo({
        content: content,
        finished: false
      });
    },
    handleDelTodo(index) {
      this.delTodo(index)
    },
    handleChangeTodo(index) {
      this.changeTodo(index)
    },
    handleSaveTodo() {
      if (this.todos.length > 0) {
        localStorage.setItem('todos', JSON.stringify(this.todos))
      }
    },
    handleClearTodo() {
      let todos = localStorage.getItem('todos')
      if (todos) {
        localStorage.clear()
      }
    },
    _loadTodoFromStorage() {
      let todos = localStorage.getItem('todos')
      if (todos)
        this.initTodo(JSON.parse(todos))
    },
    _setError(has, message) {
      this.error.has = has;
      this.error.message = message;
    },
    _initError() {
      this.error.has = false;
      this.error.message = '';
    }
  }
}
</script>

<style>
  #app {
    margin: 20px auto;
  }
</style>
